const vm = new Vue({
    el: "#base",
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            timmer: null,
            issend: false,
            ruleForm: {
                email: "",
                pass: '',
                checkPass: '',
                code: ''
            },
            user: {
                username: "",
                password: "",
                code: ""
            },
            admin: {
                username: "",
                password: ""
            },
            real_code: "",
            isadmin: false,      // 是否是管理员
            isforget: false, //忘记密码页面
            rules: {
                pass: [
                    {validator: validatePass, trigger: 'blur'}
                ],
                checkPass: [
                    {validator: validatePass2, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
                ]

            }
        }
    },
    created() {
        this.get_code()
    },
    methods: {
        // 发送邮箱
        // 验证邮箱
        regex_email(email) {
            const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            return regex.test(email);
        },
        // 发送验证码
        send_email() {
            if (!this.issend) {
                const formData = new FormData();
                formData.set("email", this.ruleForm.email)
                if (this.regex_email(this.ruleForm.email)) {
                    axios({
                        method: "post",
                        url: "/user/send",
                        data: formData
                    }).then(
                        (resp) => {
                            if (resp.data.statu) {
                                this.issend = true;

                                this.$message.success("已发送，请在邮箱中查看!")

                                clearInterval(this.timer)
                                this.timer = setInterval(
                                    () => {
                                        this.issend = false
                                    },
                                    30 * 1000)
                                this.$message.info("30s后可以重新发送")
                            } else {
                                this.$message.error(resp.data.reason)

                            }
                        }
                    )
                }
                else {
                    this.$message.error("邮箱格式不对！")
                }
            }
            else{
                this.$message.warning("已发送!")
            }
        },
        // 修改密码
        forget_pwd() {
            const formData = new FormData();
            if (this.ruleForm.pass !== this.ruleForm.checkPass) {
                this.$message.warning("两次密码不一样!")
                return
            }
            formData.set("pwd", this.ruleForm.pass);
            formData.set("email", this.ruleForm.email);
            formData.set("code", this.ruleForm.code);
            axios({
                url: "/user/forget",
                method: "post",
                data: formData
            }).then(
                (resp) => {
                    if (resp.data.statu) {
                        this.$message.success("修改成功!")
                        this.isforget = false;
                    } else {
                        this.$message.error("修改失败" + resp.data.reason)
                    }
                }
            )
        },
        get_code() {
            const string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOBQRSTUVWXYZ0123456789";
            let result = ""
            for (let i = 0; i < 4; i++) {
                const rand_s = string[Math.floor(Math.random() * string.length)]
                result += rand_s
            }
            this.real_code = result
        },
        to_Sign() {
            window.location.href = "/user/sign"
        },
        to_forget() {
            this.isforget = true;
        },
        to_home() {
            window.location.href = "/home_index"
        },
        to_admin() {
            window.location.href = "/admin_index";
        },
        login(n) {
            const that = this
            const formData = new FormData();
            if (n === 0) {
                // 验证验证码
                if (this.user.code !== this.real_code) {
                    this.$message.error("验证码错误！")
                    this.user.code = "";
                    this.get_code();
                    return;
                }
                for (let key in this.user) {
                    formData.set(key, this.user[key])
                }
            } else {
                for (let key in this.admin) {
                    formData.set(key, this.admin[key]);
                }
            }
            // 异步发送请求
            axios({
                url: "/user/login",
                method: "post",
                data: formData
            }).then(
                (resp) => {
                    if (!resp.data.statu) {
                        that.$message.error(resp.data.reason)
                        that.user = {username: "", password: "", code: ""}
                        this.get_code();
                    }
                    // 登录成功
                    else {
                        sessionStorage.setItem("user_id", resp.data.datas.user_id)
                        sessionStorage.setItem("nickName", resp.data.datas.nickName)
                        sessionStorage.setItem("img", resp.data.datas.img)
                        const notifyData = {
                            type: "success",
                            message: "登录成功!",
                            duration: 2000
                        };

                        if (resp.data.datas.isadmin) {
                            notifyData.onClose = this.to_admin;
                        } else {
                            notifyData.onClose = this.to_home;
                        }

                        this.$notify(notifyData);
                    }
                }
            )

        }
    }
})